package cc.sheji.Service;

import cc.sheji.domain.*;
import cc.sheji.exception.CodeException;
import cc.sheji.exception.NotEnoughCoinException;
import cc.sheji.exception.NotUserException;
import cc.sheji.exception.PasswordException;
import cc.sheji.reposity.InvitationListRepository;
import cc.sheji.reposity.NoticeRepository;
import cc.sheji.reposity.UserFocusRepository;
import cc.sheji.reposity.UserRepository;
import cc.sheji.util.EncoderUtil;
import cc.sheji.util.HttpUtil;
import cc.sheji.util.QueryHelp;
import cc.sheji.util.RandomUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {
    @Autowired
    UserRepository userRepository;

    @Autowired
    EncoderUtil encoderUtil;
    @Autowired
    CoinLogService coinLogService;

    @Autowired
    UserFocusRepository userFocusRepository;

    @Autowired
    NoticeRepository noticeRepository;

    @Autowired
    HttpUtil httpUtil;

    @Autowired
    MessageCodeService messageCodeService;

    @Autowired
    InvitationListRepository invitationListRepository;


    String appid = "wx85dd784a1d6ddc9d";
    //小程序secret
    String secret = "e0727eaaaf4a8462d7f1d183383d542e";


    @Autowired
    private RedisTemplate redisTemplate;


    public String getWXOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        String data = httpUtil.getToString(url);
        JSONObject jsonObject = JSONObject.parseObject(data);
        String openid = jsonObject.getString("openid");
        System.out.println("data:" + data);
        return openid;
    }

    public boolean readMeassage() {
        redisTemplate.opsForValue().set("meassageReadTime" + StpUtil.getLoginId(), System.currentTimeMillis());
        return true;
    }

    public Object getMessageInfo() {
        HashMap<String, Object> returnData = new HashMap<>();
        Sort order = Sort.by(Sort.Direction.DESC, "createTime");
        PageRequest pageable = PageRequest.of(0, 1, order);
        long time1=0L;
        {
            NoticeQueryCriteria criteria = new NoticeQueryCriteria();
            criteria.setType(3);
          //  criteria.setUserId(StpUtil.getLoginIdAsLong());
            Page<Notice> page = noticeRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                    QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
            List<Notice> content = page.getContent();

            HashMap map = new HashMap();
            if (content.size() > 0) {
                Notice notice = content.get(0);

                String timeStr = "";
               long time = System.currentTimeMillis() - notice.getCreateTime().getTime();

                if (time < 60 * 1000) {
                    timeStr = "刚刚";
                } else if (time < 60 * 1000 * 60) {
                    timeStr = "一小时内";
                } else if (time < 60 * 1000 * 60 * 24) {
                    timeStr = "一天内";
                } else {
                    timeStr = "一天前";
                }

                map.put("time", timeStr);
                map.put("notice", notice);
                returnData.put("newTaskFinish", content.get(0));
                time1=notice.getCreateTime().getTime();

            } else {
                map.put("time", "暂无");
                map.put("notice", null);
            }


            returnData.put("newSystemMsg", map);
        }

        {
            NoticeQueryCriteria criteria = new NoticeQueryCriteria();
            criteria.setType(2);
            criteria.setUserId(StpUtil.getLoginIdAsLong());
            Page<Notice> page = noticeRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                    QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
            List<Notice> content = page.getContent();

            HashMap map = new HashMap();
            if (content.size() > 0) {
                Notice notice = content.get(0);

                String timeStr = "";
                long time = System.currentTimeMillis() - notice.getCreateTime().getTime();
                if (time < 60 * 1000) {
                    timeStr = "刚刚";
                } else if (time < 60 * 1000 * 60) {
                    timeStr = "一小时内";
                } else if (time < 60 * 1000 * 60 * 24) {
                    timeStr = "一天内";
                } else {
                    timeStr = "一天前";
                }

                map.put("time", timeStr);
                map.put("notice", notice);
                returnData.put("newTaskFinish", content.get(0));
                long time2 = notice.getCreateTime().getTime();
                if(time2>time1){
                    time1=time2;
                }
            } else {
                map.put("time", "暂无");
                map.put("notice", null);
            }

            returnData.put("newTaskFinish", map);
        }
        returnData.put("newTime",time1);
        String meassageReadTimeStr =  ""+redisTemplate.opsForValue().get("meassageReadTime" + StpUtil.getLoginId());
        if("null".equals(meassageReadTimeStr)){
            meassageReadTimeStr=""+(System.currentTimeMillis()-60*1000*60*24*7);
        }
        Long meassageReadTime=Long.parseLong(meassageReadTimeStr);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        {
            NoticeQueryCriteria criteria = new NoticeQueryCriteria();
            criteria.setType(2);
            criteria.setUserId(StpUtil.getLoginIdAsLong());
            criteria.setEndDate(simpleDateFormat.format(new Date()));
            criteria.setStartDate(simpleDateFormat.format(new Date(meassageReadTime)));
            long messageNum = noticeRepository.count((root, criteriaQuery, criteriaBuilder) ->
                    QueryHelp.getPredicate(root, criteria, criteriaBuilder));
            returnData.put("newNum2", messageNum);
        }
        {
            NoticeQueryCriteria criteria = new NoticeQueryCriteria();
            criteria.setType(3);
            criteria.setUserId(StpUtil.getLoginIdAsLong());
            criteria.setEndDate(simpleDateFormat.format(new Date()));
            criteria.setStartDate(simpleDateFormat.format(new Date(meassageReadTime)));
            long messageNum = noticeRepository.count((root, criteriaQuery, criteriaBuilder) ->
                    QueryHelp.getPredicate(root, criteria, criteriaBuilder));
            returnData.put("newNum3", messageNum);
        }

        return returnData;
    }

    public HashMap loginPhone(String phone, String code) throws Exception {



        MessageCode messageCode=new MessageCode();
        messageCode.setPhone(phone);
        messageCode.setCode(code);
        boolean check = messageCodeService.check(messageCode);

        if(!check){
            throw new CodeException();
        }
        User user = userRepository.findFirstByPhone(phone);
        if (user == null) {
            throw new CodeException();
        }

        StpUtil.login(user.getId());
        HashMap returnData = userInfo(user);
        return returnData;
    }

    public HashMap login(String name, String password) throws Exception {

        User user = userRepository.findUserByName(name);
        System.out.println("password:" + password);
        String passwordEncode = encoderUtil.encodeStr(password);
        if (user == null) {
            throw new PasswordException();
        }
        System.out.println("passwordEncode:" + passwordEncode);
        if (!passwordEncode.equals(user.x())) {
            throw new PasswordException();
        }
        StpUtil.login(user.getId());
        HashMap returnData = userInfo(user);
        return returnData;
    }

    private HashMap<String, Object> userInfo(User user) {
        if("".equals(user.getInvitationCode())|| null==user.getInvitationCode()){
            //更新
            user.setInvitationCode(RandomUtil.getRandomString(8));
            user=userRepository.save(user);
        }
        HashMap returnData = new HashMap();
        returnData.put("token", StpUtil.getTokenValue());
        returnData.put("name", user.getName());
        returnData.put("avator", user.getAvator());
        returnData.put("productNum", user.getProductNum());
        returnData.put("fansNum", user.getFansNum());
        returnData.put("commentNum", user.getCommentNum());
        returnData.put("loveNum", user.getLoveNum());
        returnData.put("fucusNum", user.getFucusNum());
        returnData.put("level", user.getLevel());
        returnData.put("authState", user.getAuthState());
        returnData.put("phone", user.getPhone());
        returnData.put("coin", user.getCoin());
        returnData.put("vipNum0", user.getVipNum0());
        returnData.put("freeFastNum", user.getFreeFastNum());
        returnData.put("toDayNum", user.getToDayNum());
        returnData.put("sameProductNum", user.getSameProductNum());
        returnData.put("todaySignIn", user.getTodaySignIn());
        returnData.put("signInday", user.getSignInDay());
        returnData.put("sameNum", user.getSameNum());
        returnData.put("info", user.getInfo());
        switch (user.getLevel()) {
            case 1:
                returnData.put("vipName", "青铜金权益卡");
                returnData.put("vipTime", user.getVip1Time());
                returnData.put("vipNum", user.getVipNum1());
                break;
            case 2:
                returnData.put("vipName", "白银金权益卡");
                returnData.put("vipTime", user.getVip2Time());
                returnData.put("vipNum", user.getVipNum2());
                break;
            case 3:
                returnData.put("vipName", "黄金金权益卡");
                returnData.put("vipTime", user.getVip3Time());
                returnData.put("vipNum", user.getVipNum3());
                break;
            case 4:
                returnData.put("vipName", "铂金权益卡");
                returnData.put("vipTime", user.getVip4Time());
                returnData.put("vipNum", user.getVipNum4());
                break;
            default:
                returnData.put("vipName", "设辑AI体验卡");
                returnData.put("vipTime", new Date(System.currentTimeMillis() + 365 * 31 * 24 * 60 * 60 * 1000));
                returnData.put("vipNum", 0);
                break;

        }

        returnData.put("vip3", user.getVip3());
        returnData.put("vip2", user.getVip2());
        returnData.put("vip1", user.getVip1());
        returnData.put("vip4", user.getVip4());
        returnData.put("invitationCode",user.getInvitationCode());
        return returnData;
    }


    public HashMap<String, Object> get() {
        User user = userRepository.findById(Long.parseLong("" + StpUtil.getLoginId())).get();
        HashMap returnData = userInfo(user);
        return returnData;
    }

    public HashMap create(User user) {
        user.setVip1(0);
        user.setVip2(0);
        user.setVip3(0);
        user.setCoin(0);
        user.setVip4(0);
        user.setSameNum(10);
        user.setVipNum1(0);
        user.setVipNum2(0);
        user.setVipNum3(0);
        user.setVipNum4(0);
        user.setToDayNum(10);
        user.setFreeFastNum(0);
        user.setVipNum0(10);
        user.setFansNum(0);
        user.setFucusNum(0);
        user.setLoveNum(0);
        user.setCommentNum(0);
        user.setSameProductNum(0);
        user.setProductNum(0);
        user.setPassword(encoderUtil.encodeStr(user.x()));
        //设置邀请码 //先抛错
        user.setInvitationCode(RandomUtil.getRandomString(8));
        user = userRepository.save(user);
        StpUtil.login(user.getId());
        HashMap returnData = userInfo(user);
        return returnData;
    }


    public User update1(User user) {
        User user1 = userRepository.findById(user.getId()).get();
        Date signTime = user.getSignTime();
        if(signTime!=null){
            user1.setSignTime(signTime);
        }
        String avator = user.getAvator();
        if(avator!=null)
            user1.setAvator(avator);
        String name = user.getName();
        if(name!=null)
            user1.setName(name);

        user1.setInfo(user.getInfo());

        User returnData = userRepository.save(user1);
        return returnData;
    }

    public User update(User user) {
        User user1 = userRepository.findById(user.getId()).get();
        Date signTime = user.getSignTime();
        if(signTime!=null){
            user1.setSignTime(signTime);
        }
        String avator = user.getAvator();
        if(avator!=null)
        user1.setAvator(avator);
        //user1.setPhone(user.getPhone());

        user1.setCoin(user.getCoin());

        user1.setSameNum(user.getSameNum());

        user1.setToDayNum(user.getToDayNum());
        User returnData = userRepository.save(user1);
        return returnData;
    }

    public User addCoin(long userId, int coin) {

        User user1 = userRepository.findById(userId).get();
        coin = user1.getCoin() + coin;
        user1.setCoin(coin);
        return update(user1);
    }
        public User addCoin(long userId, AddCoin addCoin) {

        User user1 = userRepository.findById(userId).get();
        int  coin = user1.getCoin() + addCoin.coin;
        int  sameNum = user1.getSameNum() + addCoin.sameNum;
        int  todayNum = user1.getToDayNum() + addCoin.todayNum;
        user1.setCoin(coin);
        user1.setSameNum(sameNum);
        user1.setToDayNum(todayNum);
        return update(user1);
    }


    public User sign() {
        User user1 = userRepository.findById(StpUtil.getLoginIdAsLong()).get();
        if(user1.getTodaySignIn()==1)
            return user1;
        int coin = 0;
        CoinLog coinLog = new CoinLog();
        coinLog.setUserId(StpUtil.getLoginIdAsLong());
        coinLog.setUsePermission(0);
        coinLog.setUseFastPermission(0);
        coinLog.setState(1);
        coinLog.setContent("签到奖励积分");
        Integer signInday = user1.getSignInDay();
        if(signInday<6){
            user1.setSignInDay(user1.getSignInDay()+1);
            coin=2;
        }else {
            user1.setSignInDay(0);
            coin=10;
        }
        user1.setTodaySignIn(1);
        coinLog.setCoin(coin);
        coinLogService.create(coinLog);
        coin = user1.getCoin() + coin;
        user1.setCoin(coin);
        user1.setSignTime(new Date());
        return update(user1);
    }


    public User updateVip(Long userId, int vipLevel) {
        User user1 = userRepository.findById(userId).get();
        long time = 0;

        switch (vipLevel) {
            case 1:

                user1.setVip1(1);
                user1.setVipNum1(450);
                user1.setFreeFastNum(0);
                time = System.currentTimeMillis() + 31 * 24 * 60 * 60 * 1000;
                user1.setVip1Time(new Date(time));
                break;
            case 2:

                user1.setVip2(1);
                user1.setVipNum2(600);
                user1.setFreeFastNum(0);
                time = System.currentTimeMillis() + 31 * 24 * 60 * 60 * 1000 * 3;
                user1.setVip1Time(new Date(time));
                break;
            case 3:

                user1.setVip3(1);
                user1.setVipNum3(600);
                user1.setFreeFastNum(150);
                time = System.currentTimeMillis() + 31 * 24 * 60 * 60 * 1000 * 6;
                user1.setVip1Time(new Date(time));
                break;
            case 4:

                user1.setVip4(1);
                user1.setVipNum4(900);
                user1.setFreeFastNum(300);
                time = System.currentTimeMillis() + 31 * 24 * 60 * 60 * 1000 * 12;
                user1.setVip1Time(new Date(time));
                break;
        }
        userRepository.save(user1);
        return user1;
    }

    public User payTask(long userId, Map map) throws NotEnoughCoinException {

        CoinLog coinLog = new CoinLog();
        coinLog.setUserId(StpUtil.getLoginIdAsLong());
        coinLog.setUsePermission(0);
        coinLog.setUseFastPermission(0);
        coinLog.setState(2);

        User user1 = userRepository.findById(userId).get();
        Integer coin1 = (Integer) map.get("coin");
        Integer type = (Integer) map.get("type");
        Integer fastCoin = (Integer) map.get("fastCoin");
        System.out.println("have coin:" + user1.getCoin());
        System.out.println("use coin:" + coin1);
        Integer permissionTime = (Integer) map.get("permissionTime");
        System.out.println("user1:" + user1);

        System.out.println("fastCoin:" + fastCoin);
        int coin = user1.getCoin() - coin1 - fastCoin;
        System.out.println("left coin:" + coin);
        if (type == 1) {
            coinLog.setContent("普通AI生成图片");
        } else if (type == 2)  {
            coinLog.setContent("Ai快速生成图片");
        }else   {
            coinLog.setContent("Ai生图片");
        }
        coinLog.setCoin(-(coin1 + fastCoin));
        if (user1.getVipNum0() == null) {
            user1.setVipNum0(0);
        }
        if (user1.getVipNum0() > 0 && user1.getLevel() == 0 && type == 1) {
            coinLog.setUsePermission(1);
            user1.setVipNum0(user1.getVipNum0() - 1);
            coinLogService.create(coinLog);
            return update(user1);
        }
        if (coin < 0) {
            throw new NotEnoughCoinException("积分不足");
        }
        user1.setCoin(coin);
        Integer freeFastNum = user1.getFreeFastNum();
        if (type == 2 && freeFastNum > 0) {
            coinLog.setUseFastPermission(1);
            user1.setFreeFastNum(freeFastNum - 1);
        }
        long nowTime = System.currentTimeMillis();
        long time1 = user1.getVip1Time().getTime();
        long time2 = user1.getVip2Time().getTime();
        long time3 = user1.getVip3Time().getTime();
        long time4 = user1.getVip4Time().getTime();
        long num1 = user1.getVipNum1();
        long num2 = user1.getVipNum2();
        long num3 = user1.getVipNum3();
        long num4 = user1.getVipNum4();
//        switch (user1.getLevel()) {
//            case 4:
//                if (time3 > nowTime && time3 < time4 && num3 > 0) {
//
//                } else if (time2 > nowTime && time2 < time4 && num2 > 0) {
//
//                } else if (time1 > nowTime && time1 < time4 && num1 > 0) {
//
//                } else {
//                    Integer vipNum4 = user1.getVipNum4();
//                    user1.setVipNum4(vipNum4 - 1);
//                    break;
//                }
//            case 3:
//                if (time2 > nowTime && time2 < time3 && num3 > 0) {
//
//                } else if (time1 > nowTime && time1 < time3 && num1 > 0) {
//
//                } else {
//                    Integer vipNum3 = user1.getVipNum3();
//                    user1.setVipNum3(vipNum3 - 1);
//                    break;
//                }
//
//            case 2:
//                if (time1 > nowTime && time1 < time3 && num1 > 0) {
//
//                } else {
//                    Integer vipNum2 = user1.getVipNum2();
//                    user1.setVipNum2(vipNum2 - 1);
//                    break;
//                }
//            case 1:
//                Integer vipNum1 = user1.getVipNum1();
//                user1.setVipNum1(vipNum1 - 1);
//                break;
//        }

        if (user1.getLevel() > 0)
            coinLog.setUsePermission(1);
        coinLogService.create(coinLog);
        return update(user1);

    }

    public User get(Long id) {
        User user = userRepository.findById(id).get();
        user.setPassword(null);
        user.setFocused(false);
        try {
            UserFocus userFocus = userFocusRepository.findFirstByFocusUserIdAndUserId(id, StpUtil.getLoginIdAsLong());
            if (userFocus != null) {
                user.setFocused(true);
            }
        } catch (Exception e) {

        }
        return user;
    }

    public List<User> list(UserQueryCriteria criteria, Pageable pageable) {

        if (criteria.type == null)
            criteria.type = 0;

        if (criteria.type == 2) {
            criteria.setProductNum(3);
        }
        Integer orderBy=criteria.getOrderBy();
        if(orderBy==null){
            orderBy=0;
        }
        Sort order=Sort.by(Sort.Direction.DESC,"createTime");
        switch (orderBy){
            case 1:
                order=Sort.by(Sort.Direction.DESC,"monthTime");
                break;
            case 2:
                order=Sort.by(Sort.Direction.DESC,"continueTime");
                break;
        }



        pageable=PageRequest.of(pageable.getPageNumber(),pageable.getPageSize(),order);
        Page<User> page = userRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        List<User> returnList = new ArrayList<>();
        long loginId = 0L;
        try {
            loginId = StpUtil.getLoginIdAsLong();
        } catch (Exception e) {
            e.printStackTrace();
        }
        HashMap<Long, UserFocus> map = new HashMap<>();
        if (criteria.type == 2 && loginId > 0) {
            UserFocusQueryCriteria criteria1 = new UserFocusQueryCriteria();
            criteria1.setUserId(loginId);
            pageable = PageRequest.of(pageable.getPageNumber(), 100000,order);
            Page<UserFocus> page1 = userFocusRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                    QueryHelp.getPredicate(root, criteria1, criteriaBuilder), pageable);
            for (UserFocus userFocus : page1.getContent()) {
                map.put(userFocus.getFocusUserId(), userFocus);
            }
        }

        for (User user : page.getContent()) {
            System.out.println("type:" + criteria.type);
            System.out.println("user:" + user);
            if (map.containsKey(user.getId())) {
                user.setFocused(true);
            }
            System.out.println("user:" + user);
            System.out.println(user.getFormatRecentPhoto().size());
            if (criteria.type != null && criteria.type == 2 && (user.getFormatRecentPhoto().size() < 3)) {
                continue;
            }
            user.setPassword("");
            returnList.add(user);
        }

        return returnList;
    }

    public Object updatePassword(User user) throws NotUserException {
        User user1 = userRepository.findFirstByPhone(user.getPhone());
        if (user1 == null)
            throw new NotUserException();
        user1.setPassword(encoderUtil.encodeStr(user.x()));
        User returnData = userRepository.save(user1);
        return returnData;
    }

    @Transactional
    public void updateInfo() {
        userRepository.updateAll();
    }

    @Transactional
    public void updateSignInfo() {
        userRepository.updateTodaySignAll();
        userRepository.updateAll1();
    }

    public void updateInfo1() {
//        List<User> allByVip1TimeLessThan = userRepository.findAllByVip1TimeLessThan(new Date());
//        System.out.println(allByVip1TimeLessThan);
    }

    public void addFocus(Long focusId) {
        UserFocus userFocus = new UserFocus();
        userFocus.setFocusUserId(focusId);
        userFocus.setUserId(StpUtil.getLoginIdAsLong());
        userFocusRepository.save(userFocus);
    }

    public List<UserFocus> focusList(UserFocusQueryCriteria criteria, Pageable pageable) {
        UserFocusQueryCriteria criteria2 = new UserFocusQueryCriteria();
        criteria2.setUserId(StpUtil.getLoginIdAsLong());

        UserFocusQueryCriteria criteria1 = new UserFocusQueryCriteria();
        criteria1.setFocusUserId(StpUtil.getLoginIdAsLong());

        Page<UserFocus> page1 = userFocusRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root, criteria1, criteriaBuilder), pageable);

        Page<UserFocus> page2 = userFocusRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root, criteria2, criteriaBuilder), pageable);
        if (criteria.getType() == 2) {

            List<UserFocus> returnList = new ArrayList<>();

            HashMap<Long, UserFocus> map = new HashMap<>();

            for (UserFocus userFocus : page1.getContent()) {
                map.put(userFocus.getUserId(), userFocus);
            }
            for (UserFocus userFocus : page2.getContent()) {
                userFocus.setFocused(true);
                returnList.add(userFocus);
            }
            return returnList;
        } else {
            List<UserFocus> returnList = new ArrayList<>();

            HashMap<Long, UserFocus> map = new HashMap<>();

            for (UserFocus userFocus : page2.getContent()) {
                map.put(userFocus.getUserId(), userFocus);
            }
            for (UserFocus userFocus : page1.getContent()) {
                userFocus.setFocused(map.containsKey(userFocus.getFocusUserId()));
                returnList.add(userFocus);
            }
            return returnList;
        }

    }

    public UserFocus focus(UserFocus entity) {
        entity.setId(null);
        entity.setUserId(StpUtil.getLoginIdAsLong());
        User user = userRepository.findById(entity.getFocusUserId()).get();
        User oweUser = userRepository.findById(StpUtil.getLoginIdAsLong()).get();
        Integer fucusNum = oweUser.getFucusNum();
        if (fucusNum == null)
            fucusNum = 0;
        oweUser.setFucusNum(fucusNum + 1);
        userRepository.save(oweUser);
        Integer loveNum = user.getFansNum();
        if (loveNum == null)
            loveNum = 0;
        user.setFansNum(loveNum + 1);
        userRepository.save(user);
        userFocusRepository.save(entity);
        return entity;
    }

    @Transactional
    public boolean deleteFocus(UserFocus entity) {
        userFocusRepository.deleteAllByFocusUserIdAndUserId(entity.getFocusUserId(), StpUtil.getLoginIdAsLong());
        User oweUser = userRepository.findById(StpUtil.getLoginIdAsLong()).get();
        Integer fucusNum = oweUser.getFucusNum();
        if (fucusNum == null)
            fucusNum = 0;
        oweUser.setFucusNum(fucusNum + 1);
        userRepository.save(oweUser);
        User user = userRepository.findById(entity.getFocusUserId()).get();
        Integer loveNum = user.getFansNum();
        if (loveNum == null)
            loveNum = 0;
        user.setFansNum(loveNum - 1);
        userRepository.save(user);
        return true;
    }

    public boolean addCategory(ArrayList<Long> ids) {
        User user = userRepository.findById(StpUtil.getLoginIdAsLong()).get();
        List<Long> formatCategory = user.getFormatCategory();
        formatCategory.addAll(ids);
        formatCategory = new ArrayList<>(new HashSet<>(formatCategory));
        user.setFormatCategory(formatCategory);
        userRepository.save(user);
        return true;
    }

    public long vipNum() {
        try {
            return userRepository.vipNum();
        } catch (Exception e) {
            return 0L;
        }


    }

    public Long total() {

        return userRepository.count();
    }

    public void paySameProduct() {
        User user = userRepository.findById(StpUtil.getLoginIdAsLong()).get();
        Integer level = user.getLevel();
        if(level==0){
            int num = user.getSameNum() - 1;
            if(num<=0)
                num=0;
            user.setSameNum(num);
        }
        userRepository.save(user);
    }


    /**
     * 邀请用户
     * @return
     */
    public HashMap invitationUser(User user){
        HashMap userMap=create(user);
        if(!"".equals(user.getInviteeCode())&&user.getInviteeCode()!=null){
            User invitationUser=userRepository.findFirstByInvitationCode(user.getInviteeCode());
            if(invitationUser!=null){
                InvitationList entity=new InvitationList();
                entity.setInvitationUser(invitationUser.getId());
                entity.setInvitees(StpUtil.getLoginIdAsLong());
                entity.setAward(50L);
                invitationListRepository.save(entity);
            }

        }
        return  userMap;
    }


}
